package cn.caplike.demo.repository.javassist;

import javassist.*;

public class ModifyTarget {

    // todo: 防止重复执行导致插入多条相同的代码片段
    private static void modify() throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get("cn.caplike.demo.repository.javassist.Target");

        CtMethod setter = cc.getDeclaredMethod("setName", pool.get(new String[]{"java.lang.String"}));
        setter.insertBefore("System.out.println(\"This method has been modified.\");");
        setter.insertAfter("super.put(\"name\", name);");

        try {
            //新增一个方法
            CtMethod ctMethod = new CtMethod(CtClass.voidType, "newGenerated", new CtClass[]{}, cc);
            ctMethod.setModifiers(Modifier.PUBLIC);
            ctMethod.setBody("{System.out.println(\"This method is totally new.\");}");
            cc.addMethod(ctMethod);
        } catch (CannotCompileException e) {
            System.err.println("Cannot compile due to `" + e.getReason() + "`");
        }

        cc.writeFile(CreatePerson.getClassPath()); // 覆盖源 Class 文件
    }

    public static void main(String[] args) throws Exception {
        modify();

        final Target target = new Target();
        target.setName("LiKe");
        System.out.println(target.getName());
        target.newGenerated();
    }
}
